#include "../Include/ThreadTask.h"


//	Thread methods
DWORD WINAPI ProcessThread(void *param)
{
	if (param)
	{
		ThreadTask* thread = (ThreadTask*)param;
		thread->ProcessTask();
	}
	return 0;
}


ThreadTask::ThreadTask() :
	mProcEvent(INVALID_HANDLE_VALUE),
	mThreadHnd(NULL),
	mThreadId(0),
	mThreadHalt(false),
	mInterval(0),
	mStarted(false)
{
	
}

ThreadTask::~ThreadTask(void)
{
	Stop();
}

void ThreadTask::Start(int interval)
{
	if(!mStarted)
	{
		mStarted = true;
		mInterval = interval;
		mProcEvent = CreateEvent(NULL, true, false, NULL);			//	manual reset, initial state reset
		mThreadHnd = CreateThread(NULL, 0, &ProcessThread, this, CREATE_SUSPENDED, &mThreadId);
		
		if (mThreadHnd)
		{
			SetThreadPriority(mThreadHnd,THREAD_PRIORITY_NORMAL);
			ResumeThread(mThreadHnd);
		}
	}
}

void ThreadTask::Stop()
{
	if(mStarted)
	{
		mThreadHalt = true;

		// Signal the event
		SetEvent(mProcEvent);

		// Wait for the Thread to Die
		WaitForSingleObject(mThreadHnd, INFINITE);
		CloseHandle(mThreadHnd);

		CloseHandle(mProcEvent);
		mStarted = false;
	}
}

void ThreadTask::ProcessTask()
{
	while (!mThreadHalt)
	{
		WaitForSingleObject(mProcEvent, mInterval); //INFINITE
		ResetEvent(mProcEvent);
		
		//process by subclass
		Process();
	}
}

